package com.lori.netshop.service.imp;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import sun.rmi.rmic.iiop.ValueType;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lori.netshop.dao.RedisDao;
import com.lori.netshop.mapper.TbContentMapper;
import com.lori.netshop.pojo.TbContent;
import com.lori.netshop.pojo.TbContentExample;
import com.lori.netshop.pojo.TbContentExample.Criteria;
import com.lori.netshop.service.ContentService;
import com.lori.netshop.util.NetshopResult;
import com.lori.netshop.util.StringUtil;
@Service
public class ContentServiceimp implements ContentService {
	//注入mapper
	@Autowired
	private TbContentMapper tbContentMapper;
	@Autowired
	private RedisDao redisDaoimp;
	@Value("${INDEX_CONTENT_REDIS_KEY}")
	private String INDEX_CONTENT_REDIS_KEY;
	@Override
	public List<TbContent> findContents(long categoryId) {
		ObjectMapper object = null;
		//将缓存中的数据取出
		try {
			//从redis集群获取数据
			String data = redisDaoimp.hget(INDEX_CONTENT_REDIS_KEY, categoryId+"");
			if(!StringUtil.isEmpty(data)){
				object = new ObjectMapper();
				JavaType javaType = object.getTypeFactory().constructParametricType(ArrayList.class, TbContent.class);
				List<TbContent> readValue = object.readValue(data, javaType);
				return readValue;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		//设置查询条件
		TbContentExample example = new TbContentExample();
		Criteria criteria = example.createCriteria();
		criteria.andCategoryIdEqualTo(categoryId);
		//获得数据
		List<TbContent> contents = tbContentMapper.selectByExampleWithBLOBs(example);
		//将查询得来的数据存入redis缓存中
		try {
			//将数据转成字符串
			object = new ObjectMapper();
			String json = object.writeValueAsString(contents);
			//将数据存入redis缓存中
			redisDaoimp.hset(INDEX_CONTENT_REDIS_KEY, categoryId+"", json);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return contents;
	}

}
